<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace frontend\logics;

use common\models\UserModel;
use common\models\UserTokenModel;
use yii\db\Exception;

class UsersLogic extends BaseLogic
{
    /**
     * 用户登录.
     * @throws Exception
     */
    public static function login(array $params = []): array|bool
    {
        if (empty($params)) {
            return self::setError('params empty');
        }

        if (empty($params['email']) || empty($params['password'])) {
            return self::setError('params error');
        }
        $user = UserModel::findByEmail($params['email']);
        if (empty($user) || ! $user->validatePassword($params['password'])) {
            return self::setError('user not found');
        }
        $token = self::getToken($user->id);
        if ($token === false) {
            return false;
        }
        return [
            'name' => $user->name,
            'email' => $user->email,
            'token' => $token,
        ];
    }

    /**
     * 获取token.
     * @throws Exception
     */
    public static function getToken(int $userId = 0): bool|string
    {
        $model = UserTokenModel::findOne(['user_id' => $userId]);
        if (! $model instanceof UserTokenModel) {
            $model = new UserTokenModel();
            $model->user_id = $userId;
        }
        $model->token = md5(uniqid((string) rand(), true));
        $model->expire_time = time() + 60 * 60 * 24 * 30;
        if ($model->save()) {
            return $model->token;
        }
        return self::setError(YII_DEBUG ? json_encode($model->getErrors()) : 'create token error');
    }

    /**
     * 用户注册.
     * @throws Exception
     */
    public static function register(array $params = []): bool
    {
        if (empty($params['email']) || empty($params['password']) || empty($params['name'])) {
            return self::setError('params error');
        }
        $user = UserModel::findOne(['email' => $params['email']]);
        if ($user instanceof UserModel && $user->id) {
            return true;
        }
        $user = new UserModel();
        $user->email = $params['email'];
        $user->name = $params['name'];
        $user->setPassword($params['password']);
        if ($user->save(false)) {
            return true;
        }
        return self::setError('create user error');
    }

    public static function logout() {}
}
